var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var lastTime = null;
var app = getApp();
Page({
  data: {
    isMultiOrderModel: 0,
    shoppingCart: {},
    orderAddress: {},
    mendian: {},
    shangpinheji: 0.00, //商品总价
    yunfei: 0.00, //快递费
    shifujine: 0.00, //实际需要支付的总价
    tablename: '', //如果是mt_pintuan则单独显示商品单价
    buytype: 0, //0为拼团购买，1为单独购买 2为跟团购买
    shoppingcartid: '',
    addressId: '',
    mendianid: '',
    type: 0,
    message: '',
    orderId: '',
    pk_mtTuzhang_pintuan: '', //如果是拼团，且是跟团的则进团开团信息
    jifen: 0, //如果是积分商城的积分兑换商品
  },
  onLoad: function (option) {
    let that = this;
    var shoppingcartid = wx.getStorageSync('shoppingcartid');
    if (shoppingcartid) {
      that.setData({
        shoppingcartid: shoppingcartid
      });
    }
    /**
     * 此参数是由拼团详情页传至当前页面的，是为了记录下来这笔订单是有哪个拼团而来的，以及该团的团长、团的有效时间、
     * 需要多少人拼团才能成
     * 用处为记录下来哪些会员跟团进行下订单。（拼团活动专用）
     */
    // 如果存在则是拼团活动，且已开团了的拼团活动
    if (option.pk_mtTuzhang_pintuan) {
      that.setData({
        pk_mtTuzhang_pintuan: option.pk_mtTuzhang_pintuan
      });
    }
    that.getorderInfo();
  },

  //获取order信息
  getorderInfo: function () {
    let that = this;
    util.request(api.MarketingOrder, {
      shoppingcartid: that.data.shoppingcartid
    }, 'Post').then(function (res) {
      if (res.result == 1) {
        that.setData({
          shoppingCart: res.data.shoppingCart,
          shangpinheji: res.data.shangpinheji,
          yunfei: res.data.yunfei
        });
        that.setData({
          tablename: res.data.shoppingCart.tablename,
          buytype: res.data.shoppingCart.buytype
        });
      }
      if (that.data.type == 0) {
        that.setData({
          shifujine: that.data.shangpinheji + that.data.yunfei
        });
      } else {
        that.setData({
          shifujine: that.data.shangpinheji
        });
      }
      if (res.data.shoppingCart.tablename == 'mt_jifenduihuan') {
        that.setData({
          jifen: res.data.shoppingCart.jifen
        });
      }
      wx.hideLoading();
    });
  },

  navmarketinggoods: function (e) {
    var tablename = e.currentTarget.dataset.tablename;
    var pk_marketing = e.currentTarget.dataset.pk_marketing;
    //点击商品中的信息时跳转至商品详情页，pk_marketing为营销活动的id
    if (tablename == 'mt_groupbuying') {
      wx.navigateTo({
        url: '/pages/marketing/groupbuying/groupbuyingDetail/groupbuyingDetail?id=' + pk_marketing
      })
    } else if (tablename == 'mt_seckill') {
      wx.navigateTo({
        url: '/pages/marketing/seckill/seckillDetail/seckillDetail?id=' + pk_marketing
      })
    } else if (tablename == 'mt_pintuan') {
      wx.navigateTo({
        url: '/pages/marketing/pintuan/pintuanDetail/pintuanDetail?id=' + pk_marketing
      })
    }
  },

  //选择地址回调
  getaddress: function () {
    let that = this;
    util.request(api.MarketingOrderAddress, {
      addressId: that.data.addressId,
      mendianid: that.data.mendianid
    }, 'Post').then(function (res) {
      if (res.result == 1) {
        if (res.data.orderAddress) {
          that.setData({
            orderAddress: res.data.orderAddress,
          });
        }
        if (res.data.mendian) {
          that.setData({
            mendian: res.data.mendian,
          });
        }
        if (that.data.type == 0) {
          that.setData({
            shifujine: that.data.shangpinheji + that.data.yunfei
          });
        } else {
          that.setData({
            shifujine: that.data.shangpinheji
          });
        }
      }
      wx.hideLoading();
    });
  },

  switchTab: function (e) {
    let that = this;
    that.setData({
      type: e.currentTarget.dataset.index,
    });
    if (that.data.type == 0) {
      that.setData({
        shifujine: that.data.shangpinheji + that.data.yunfei
      });
    } else {
      that.setData({
        shifujine: that.data.shangpinheji
      });
    }
  },
  //选择收货地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/ucenter/address/address',
    })
  },
  //选择门店地址
  selectMendian() {
    wx.navigateTo({
      url: '/pages/ucenter/guanli/mendian/mendian',
    })
  },
  bindMessageInput: function (e) {
    this.setData({
      message: e.detail.value
    });
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    var that = this;
    try {
      var addressid = wx.getStorageSync('addressid');
      if (addressid) {
        that.setData({
          'addressId': addressid
        });
      }
      var mendianid = wx.getStorageSync('mendianid');
      if (mendianid) {
        that.setData({
          'mendianid': mendianid
        });
      }
    } catch (e) {
      // Do something when catch error
      console.log(e);
    }
    that.getaddress();
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },

  //确认提交订单
  submitOrder: function () {
    let that = this;
    var submityunfei = 0;
    if (that.data.type == 0) {
      if (that.data.addressId == '') {
        util.showErrorToast('请选择收货地址');
        return false;
      }
      submityunfei = that.data.yunfei;
    }
    if (that.data.type == 1) {
      if (!that.data.mendian.id) {
        util.showErrorToast('请选择门店地址');
        return false;
      }
      submityunfei = 0;
    }
    util.jhxLoadShow("正在下单，请稍后...");
    let nowTime = +new Date();
    if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
      lastTime = nowTime;
    } else {
      return false;
    }
    util.jhxLoadHide();
    /**
     * pk_mtTuzhang_pintuan此参数是由拼团详情页传至当前页面的，是为了记录下来这笔订单是有哪个拼团而来的，
     * 以及该团的团长、团的有效时间、需要多少人拼团才能成
     * 用处为记录下来哪些会员跟团进行下订单。（拼团活动专用）
     */
    util.request(api.MarketingOrderSubmit, {
      shoppingcartid: that.data.shoppingcartid,
      addressId: that.data.addressId,
      mendianid: that.data.mendianid,
      message: that.data.message,
      shangpinheji: that.data.shangpinheji,
      shifujine: that.data.shifujine,
      yunfei: submityunfei,
      pk_mtTuzhang_pintuan: that.data.pk_mtTuzhang_pintuan,
      jifen: that.data.jifen,
      shouhuotype: that.data.type,
    }, 'POST').then(res => {
      that.setData({
        orderId: res.data.orderId
      });
      if (res.result == 1) {
        let memberUserid = wx.getStorageSync('memberUserid');
        util.request(api.OrderPrepay, {
          memberUserid: memberUserid,
          orderId: that.data.orderId,
          amount_total: that.data.shifujine
        }, 'POST').then(function (res) {
          if (res.result == 1) {
            const payParam = res.data;
            console.log("支付过程开始");
            wx.requestPayment({
              'timeStamp': payParam.timeStamp,
              'nonceStr': payParam.nonceStr,
              'package': payParam.package,
              'signType': payParam.signType,
              'paySign': payParam.paySign,
              'success': function (res) {
                console.log("支付过程成功");
                wx.redirectTo({
                  url: '/pages/payResult/payResult?status=1&orderId=' + that.data.orderId
                });
              },
              'fail': function (res) {
                console.log("支付过程失败");
                wx.redirectTo({
                  url: '/pages/payResult/payResult?status=0&orderId=' + that.data.orderId
                });
              },
              'complete': function (res) {
                console.log("支付过程结束");
                wx.requestSubscribeMessage({
                  tmplIds: app.globalData.tmplIds,
                  success(res) {
                    util.request(api.Ordermessage, {
                      orderId: that.data.orderId
                    }, 'POST').then(function (res) {
                    });
                  }
                })
              }
            });
          } else {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=0&orderId=' + that.data.orderId
            });
          }
        });
      } else {
        wx.redirectTo({
          url: '/pages/payResult/payResult?status=0&orderId=' + orderId
        });
      }
    });
  }
});